<?php

namespace App\Http\Controllers\Admin\MallManager;

use App\Http\Controllers\BaseController;
use App\Services\Tools\CommonService;
use Illuminate\Support\Facades\Log;
use function Clue\StreamFilter\fun;
use Illuminate\Http\Request;

//引用http请求类
use App\Exceptions\BasicException;

//引入框架异常处理类
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

//引入hash
use App\Services\Cache\AdminCacheService;

//admin缓存
use App\Services\Tools\JwtService;

//引入JWT服务
use App\Services\Tools\FileService;

//引入文件处理类
use App\Response\Response;
use Illuminate\Support\Facades\Redis;
use App\Services\Tools\ExportService;

//引入导出服务


class MallController extends BaseController
{

    /**
     * @api {post} /mall/mall_type_list 商城分类-列表
     * @apiVersion 0.1.0
     * @apiName 商城分类-列表
     * @apiGroup 个性商城
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": [
     * {
     * "id（主键序号）": 1,
     * "title（名称）": "挂件"
     * }
     * ]
     * }
     */
    public function mall_type_list()
    {
        $list = app('repo_mall_categories')->getCategoryList();
        return Response::sendData($list);
    }

    /**
     * @api {post} /mall/mall_type_add 商城分类-新增
     * @apiVersion 0.1.0
     * @apiName 商城分类-新增
     * @apiGroup 个性商城
     * @apiParam {string} title     分类名称，必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */
    public function mall_type_add(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'title' => 'required|between:1,30',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));
        $param = $request->only(['title']);
        $param['add_time'] = time();
        app('repo_mall_categories')->addType($param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /mall/mall_type_save 商城分类-编辑
     * @apiVersion 0.1.0
     * @apiName 商城分类-编辑
     * @apiGroup 个性商城
     * @apiParam {number} id     主键id，必传
     * @apiParam {string} title     分类名称，必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */
    public function mall_type_save(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|numeric',
                'title' => 'required|between:1,30',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));
        $param = $request->only(['id', 'title']);
        app('repo_mall_categories')->saveType($param);
        return Response::sendData(true);
    }

    /**
     * @api {post} /mall/mall_type_del 商城分类-删除
     * @apiVersion 0.1.0
     * @apiName 商城分类-删除
     * @apiGroup 个性商城
     * @apiParam {string} ids     主键id（多个用逗号隔开），必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": true
     * }
     */

    public function mall_type_del(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'ids' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $ids = $request->input('ids');
        $ids = explode(',', $ids);
        app('repo_mall_categories')->delType($ids);
        return Response::sendData(true);
    }


    /**
     * @api {post} /mall/mall_product_list 商城产品-列表
     * @apiVersion 0.1.0
     * @apiName 商城产品-列表
     * @apiGroup 个性商城
     * @apiParam {number} show_type     1公屏位置2全屏，非必传
     * @apiParam {number} on_sale     是否在出售：1是 2否，非必传
     * @apiParam {number} category_id    分类id，非必传
     * @apiParam {string}  add_time      查询当天的数据，非必传
     * @apiParam {string} title    产品名称，非必传
     * @apiParam {number} free    是否免费:1是  2否，非必传
     * @apiParam {number} forever    是否永久:1是  2不是，非必传
     * @apiParam {number} day    天数，非必传
     * @apiParam {number} price    价格，非必传
     * @apiParam {number} page    页数（不传默认为1），非必传
     * @apiParam {number} perPage   每页数量，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list(数据列表)": [
     * {
     * "id": 29,
     * "category_id（分类id）": 2,
     * "title（标题）": "银光天马",
     * "add_time（添加时间）": "2020-05-29 17:32:59",
     * "picture（图片）": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5ed779265eb09.png",
     * "special（特效图）": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5ed7769c37ceb.svga",
     * "on_sale（是否再出售：1是 2否）": 1,
     * "category_name（分类名称）": "坐骑",
     * "show_type（1公屏位置2全屏）": "1",
     * "mall_products_price（商品价格）": [
     * {
     * "id（商品价格主键id）": 29,
     * "product_id（商品id）": 29,
     * "price（价格：0 免费 ）": 0,
     * "day（天数：9999 永久 ）": 1
     * }
     * ]
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 20,
     * "next": null,
     * "total": 1
     * },
     * "header": {
     * "on_sale（是否再出售：1是 2否）": "1",
     * "category_id（分类id）": "2",
     * "add_time（搜索时间）": "2020-05-29",
     * "title（标题）": "银",
     * "free（是否免费：1是  2否）": "1",
     * "forever（是否永久 ： 1是  2否）": "2",
     * "day（天数）": "1",
     * "show_type（1公屏位置2全屏）": "1",
     * "price（价格）": "0"
     * }
     * }
     * }
     *
     */
    public function mall_product_list(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'on_sale' => 'filled|in:1,2',
                'category_id' => 'filled|numeric',
                'add_time' => 'filled|date_format:"Y-m-d"',
                'title' => 'filled',
                'free' => 'filled|in:1,2',
                'show_type' => 'filled|in:1,2',
                'forever' => 'filled|in:1,2',
                'day' => 'filled|numeric',
                'price' => 'filled|numeric',
                'page' => 'filled|numeric',
                'perPage' => 'filled|numeric',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $param = $request->only(['on_sale', 'category_id', 'add_time', 'title', 'free', 'forever', 'day', 'price', 'show_type']);
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 20);
        $where_product = $where_price = [];
        if (isset($param['on_sale'])) {
            $where_product[] = ['on_sale', $param['on_sale']];
        }
        if (isset($param['show_type'])) {
            $where_product[] = ['show_type', $param['show_type']];
        }
        if (isset($param['category_id'])) {
            $where_product[] = ['category_id', $param['category_id']];
        }
        if (isset($param['add_time'])) {
            $search_time = [strtotime($param['add_time']), strtotime($param['add_time']) + 86400];
            $where_product[] = [function ($query) use ($search_time) {
                $query->whereBetween('add_time', $search_time);
            }];
        }
        if (isset($param['title'])) {
            $title = $param['title'];
            $where_product[] = [function ($query) use ($title) {
                $query->where('title', 'like', "%{$title}%");
            }];
        }
        if (isset($param['free'])) {
            if ($param['free'] == 1) {
                $where_price[] = ['price', 0];
            } elseif ($param['free'] == 2) {
                $where_price[] = ['price', '>', 0];
            }
        }
        if (isset($param['price'])) {
            $where_price[] = ['price', $param['price']];
        }
        if (isset($param['forever'])) {
            if ($param['forever'] == 1) {
                $where_price[] = ['day', 9999];
            } elseif ($param['forever'] == 2) {
                $where_price[] = ['day', '<', 9999];
                $where_price[] = ['day', '>', 0];
            }
        }
        if (isset($param['day'])) {
            $where_price[] = ['day', $param['day']];
        }
        $list = app('repo_mall_products')->productList($where_product, $where_price, $page, $perPage);
        if ($list) {
            foreach ($list as $key => $value) {
                $value->add_time = date('Y-m-d H:i:s', $value->add_time);
                if (isset($value->mall_categories->category_name)) {
                    $value->category_name = $value->mall_categories->category_name;
                } else {
                    $value->category_name = '未知分类';
                }
                unset($value->mall_categories);

            }
        }
        return Response::sendList($list, [], $param);
    }

    /**
     * @api {post} /mall/mall_search_list 商城产品-搜索条件
     * @apiVersion 0.1.0
     * @apiName 商城产品-搜索条件
     * @apiGroup 个性商城
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "on_sale(是否出售)": {
     * "1": "出售中",
     * "2": "非卖品"
     * },
     * "free（是否免费）": {
     * "1": "免费",
     * "2": "收费"
     * },
     * "forever（是否永久）": {
     * "1": "永久",
     * "2": "不永久"
     * },
     * "use_status（使用状态）": {
     * "2": "已过期",
     * "1": "使用中",
     * "0": "未使用"
     * },
     * "category_list（分类列表）": [
     * {
     * "id（主键ID）": 1,
     * "title（分类名称）": "挂件"
     * }
     * ]
     * }
     * }
     */
    public function mall_search_list()
    {
        //是否出售：1是 2否
        $on_sale = [
            '1' => '出售中',
            '2' => '非卖品',
        ];
        //是否免费：1 免费 2 收费
        $free = [
            '1' => '免费',
            '2' => '收费',
        ];
        //是否永久：1 永久  2不永久
        $forever = [
            '1' => '永久',
            '2' => '不永久',
        ];

        //产品使用状态
        $use_status = [
            '2' => '已过期',
            '1' => '使用中',
            '0' => '未使用',
        ];

        //产品分类
        $category_list = app('repo_mall_categories')->getCategoryList();
        $data = [
            'on_sale' => $on_sale,
            'free' => $free,
            'forever' => $forever,
            'use_status' => $use_status,
            'category_list' => $category_list,
        ];
        return Response::sendData($data);
    }


    /**
     * @api {post} /mall/mall_product_add 商城产品-新增
     * @apiVersion 0.1.0
     * @apiName 商城产品-新增
     * @apiGroup 个性商城
     *
     * @apiParam {number} category_id     产品分类id，必传
     * @apiParam {string} title    标题，必传
     * @apiParam {number} show_type      显示位置：1公屏 2全屏，必传
     * @apiParam {string} picture    图片，必传
     * @apiParam {string} special    效果图片，非必传
     * @apiParam {array}  day_price(day,price)   天数和价格 （二维数组），非必传
     * @apiParam {number} on_sale   是否出售：1是 2否，必传
     *
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     */
    public function mall_product_add(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'category_id' => 'required|numeric',
                'title' => 'required|between:1,30',
                'show_type' => 'required|in:1,2,3',
                'picture' => 'required|string|active_url',
                'special' => 'filled|string',
                'day_price' => 'filled|array',
                'on_sale' => 'required|in:1,2',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $param = $request->only(['category_id', 'title', 'show_type', "picture", "special", 'on_sale']);

        $day_price = $request->input('day_price', '');

        $param['add_time'] = time();
        $add = app('repo_mall_products')->addProduct($param);

        if ($add && $day_price) {
            $day_price_arr = [];
            foreach ($day_price as $key => $value) {
                if (!isset($value['day']) || !$value['day'] || !isset($value['price']) || !$value['price']) {
                    continue;
                }
                $value['product_id'] = $add->id;
                $day_price_arr[] = $value;
            }
            if ($day_price_arr) {
                app('repo_mall_products_price')->addProductPrice($day_price_arr);
            }
        }

        return Response::sendData(true);
    }


    /**
     * @api {post} /mall/mall_product_save 商城产品-编辑
     * @apiVersion 0.1.0
     * @apiName 商城产品-编辑
     * @apiGroup 个性商城
     *
     * @apiParam {number} id     产品主键id，必传
     * @apiParam {number} category_id     产品分类id，必传
     * @apiParam {string} title    标题，必传
     * @apiParam {number} show_type      显示位置：1公屏 2全屏，必传
     * @apiParam {string} picture    图片，必传
     * @apiParam {string} special    效果图片，非必传
     * @apiParam {array}  day_price(id,day,price)   天数和价格 （二维数组），非必传
     * @apiParam {number} on_sale   是否出售：1是 2否，必传
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     */
    public function mall_product_save(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|numeric',
                'category_id' => 'required|numeric',
                'title' => 'required|between:1,30',
                'show_type' => 'required|in:0,1,2',
                'picture' => 'required|string|active_url',
                'day_price' => 'filled|array',
                'on_sale' => 'required|in:1,2',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $param = $request->only(['id', 'category_id', 'title', 'show_type', 'on_sale', 'special', 'picture']);
        $day_price = $request->input('day_price', '');
        DB::connection("mysql")->transaction(function () use ($param, $day_price) {
            app('repo_mall_products')->saveProduct($param);
            if ($day_price) {
                app('repo_mall_products_price')->delProductPrice([$param['id']]);
                foreach ($day_price as $key => $value) {
                    if (!isset($value['day']) || !$value['day'] || !isset($value['price']) || !$value['price']) {
                        continue;
                    }
                    $value['product_id'] = $param['id'];
                    $value['original_price'] = $value['price'];
                    app('repo_mall_products_price')->addProductPrice($value);
                }
            }
        }, 5);

        return Response::sendData(true);
    }

    /**
     * @api {post} /mall/mall_product_del 商城产品-删除
     * @apiVersion 0.1.0
     * @apiName 商城产品-删除
     * @apiGroup 个性商城
     * @apiParam {number} ids     产品主键(多个用逗号隔开)，必传
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     */
    public function mall_product_del(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'ids' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $ids = $request->input('ids');
        $ids = explode(',', $ids);
        $del = app('repo_mall_products')->delProduct($ids);
        if ($del) {
            app('repo_mall_products_price')->delProductPrice($ids);
        }
        return Response::sendData(true);
    }

    /**
     * @api {post} /mall/mall_product_detail 商城产品-详情
     * @apiVersion 0.1.0
     * @apiName 商城产品-详情
     * @apiGroup 个性商城
     * @apiParam {number} id     产品主键，必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "id(产品主键id)": 93,
     * "category_id（产品分类id）": 3,
     * "title（标题）": "靓号:286128",
     * "add_time（时间）": 1598602739,
     * "picture（图片）": "",
     * "special（特效图）": "",
     * "on_sale（是否出售：1是  2否）": 2,
     * "show_type（显示位置：1公屏2全屏）": 1,
     * "mall_products_price（产品价格列表）": [
     * {
     * "id（产品价格id）": 61,
     * "product_id（产品id）": 93,
     * "day（天数）": 10,
     * "price（价格）": 10
     * }
     * ]
     * }
     * }
     */
    public function mall_product_detail(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required',
            ]
        );
        if ($v->fails()) throw new BasicException(10001);
        $id = $request->input('id');
        $where[] = ['id', $id];
        $detail = app('repo_mall_products')->productDetail($where);
        return Response::sendData($detail);
    }

    /**
     * @api {post} /mall/mall_product_give 商城产品-赠送
     * @apiVersion 0.1.0
     * @apiName 商城产品-赠送
     * @apiGroup 个性商城
     *
     * @apiParam {number} id     产品主键，必传
     * @apiParam {number} user_code   用户编号，必传
     * @apiParam {number} use_days     使用天数，必传
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     */

    public function mall_product_give(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required',
                'user_code' => 'required|numeric',
                'use_days' => 'required|numeric|min:1',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));
        $param = $request->only(['id', 'user_code', 'use_days']);
        $where_user[] = ['user_code', $param['user_code']];
        $user_id = app('repo_user_data')->getUserId($where_user);

        $where[] = ['id', $param['id']];
        $detail = app('repo_mall_products')->productDetail($where);

        if ($detail) {
            app("repo_mall_orders")->give($param['id'], $user_id, $param['use_days']);
        } else {
            throw new BasicException(50005);
        }

        return Response::sendData(true);
    }

    /**
     * @api {post} /mall/mall_order_list 产品购买记录列表
     * @apiVersion 0.1.0
     * @apiName 产品购买记录列表
     * @apiGroup 个性商城
     * @apiParam {string} user_id_buyer     购买人，非必传
     * @apiParam {string} user_id_owner   拥有人，非必传
     * @apiParam {string} title     产品名称，非必传
     * @apiParam {number} category_id     产品分类id，非必传
     * @apiParam {string} add_time     购买时间，非必传
     * @apiParam {string} expired_time     过期时间，非必传
     * @apiParam {number} renew_count     续费次数，非必传
     * @apiParam {number} state     是否使用：0未使用1使用中2已过期，非必传
     * @apiParam {number} free     是否免费：1是 2否，非必传
     * @apiParam {number} forever     是否永久：1是  2否，非必传
     * @apiParam {number} day     天数，非必传
     * @apiParam {number} price     价格，非必传
     * @apiParam {number} page     页数（不传默认第一页），非必传
     * @apiParam {number} perPage     每页数据数量，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id(主键序号)": 434,
     * "user_id_buyer(购买者id)": 642801,
     * "user_id_owner（拥有者id）": 642801,
     * "product_id（产品id）": 29,
     * "price_id（价格id）": 29,
     * "expired_time（过期时间）": "2020-09-08 14:14:38",
     * "renew_count（续费次数）": 0,
     * "price（产品价格）": "免费",
     * "day（天数）": 1,
     * "state（使用状态：0未使用1使用中2已过期）": 2,
     * "add_time（购买时间）": "2020-09-07 14:14:38",
     * "category_id（分类id）": 2,
     * "buyer_nickname（购买者昵称）": "气泡用户859186",
     * "owner_nickname（拥有者昵称）": "气泡用户859186",
     * "product_name（产品名称）": "银光天马",
     * "product_picture（产品图片）": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5ed779265eb09.png",
     * "category_name（产品分类名称）": "坐骑",
     * "use_status（使用状态）": "已过期"
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 20,
     * "next": null,
     * "total": 1
     * },
     * "header": {
     * "user_id_buyer（搜索购买者）": "气泡",
     * "user_id_owner（搜索拥有者）": "气泡",
     * "title（产品标题）": "银光",
     * "category_id（分类id）": "2",
     * "add_time（购买时间）": "2020-09-07",
     * "expired_time（过期时间）": "2020-09-08",
     * "renew_count（续费次数）": "0",
     * "state（使用状态）": "2",
     * "free（是否免费）": "1",
     * "forever（是否永久）": "2",
     * "day（天数）": "1",
     * "price（产品价格）": "0"
     * }
     * }
     * }
     */

    public function mall_order_list(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'user_id_buyer' => 'filled',
                'user_id_owner' => 'filled',
                'title' => 'filled',
                'category_id' => 'filled|numeric',
                'add_time' => 'filled|date_format:"Y-m-d"',
                'expired_time' => 'filled|date_format:"Y-m-d"',
                'renew_count' => 'filled|numeric',
                'state' => 'filled|in:0,1,2',
                'free' => 'filled|in:1,2',
                'forever' => 'filled|in:1,2',
                'day' => 'filled|numeric',
                'price' => 'filled|numeric',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $param = $request->only(['user_id_buyer', 'user_id_owner', 'title', 'category_id', 'add_time', 'expired_time', 'renew_count', 'state', 'free', 'forever', 'day', 'price']);
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 20);
        $where_buyer = $where_owner = $where_product = $where_order = [];
        if (isset($param['user_id_buyer'])) {
            $user_id_buyer = $param['user_id_buyer'];
            $where_buyer[] = [function ($query) use ($user_id_buyer) {
                $query->where('nickname', 'like', "%{$user_id_buyer}%");
            }];
        }
        if (isset($param['user_id_owner'])) {
            $user_id_owner = $param['user_id_owner'];
            $where_owner[] = [function ($query) use ($user_id_owner) {
                $query->where('nickname', 'like', "%{$user_id_owner}%");
            }];
        }
        if (isset($param['title'])) {
            $title = $param['title'];
            $where_product[] = [function ($query) use ($title) {
                $query->where('title', 'like', "%{$title}%");
            }];
        }

        if (isset($param['category_id'])) {
            $where_product[] = ['category_id', $param['category_id']];
        }

        if (isset($param['add_time'])) {
            $add_time = strtotime($param['add_time']);
            $where_order[] = [function ($query) use ($add_time) {
                $query->whereBetween('add_time', [$add_time, $add_time + 86400]);
            }];
        }
        if (isset($param['expired_time'])) {
            $expired_time = strtotime($param['expired_time']);
            $where_order[] = [function ($query) use ($expired_time) {
                $query->whereBetween('expired_time', [$expired_time, $expired_time + 86400]);
            }];
        }
        if (isset($param['renew_count'])) {
            $where_order[] = ['renew_count', $param['renew_count']];
        }
        if (isset($param['state'])) {
            $where_order[] = ['state', $param['state']];
        }
        if (isset($param['free'])) {
            if ($param['free'] == 1) {
                $where_order[] = ['price', 0];
            }
            if ($param['free'] == 2) {
                $where_order[] = ['price', '>', 0];
            }
        }
        if (isset($param['price'])) {
            $where_order[] = ['price', $param['price']];
        }
        if (isset($param['forever'])) {
            if ($param['forever'] == 1) {
                $where_order[] = ['day', 9999];
            }
            if ($param['forever'] == 2) {
                $where_order[] = ['day', '>', 0];
                $where_order[] = ['day', '<', 9999];
            }
        }


        if (isset($param['day'])) {
            $where_order[] = ['day', $param['day']];
        }
        $all_where = [
            'where_buyer' => $where_buyer,
            'where_owner' => $where_owner,
            'where_product' => $where_product,
            'where_order' => $where_order,
        ];
        $list = app('repo_mall_orders')->MallOrderList($all_where, $page, $perPage);

        if ($list) {
            foreach ($list as $key => $value) {
                $value->buyer_nickname = $value->user_buyer->nickname ?? '';
                $value->owner_nickname = $value->user_owner->nickname ?? '';
                $value->product_name = $value->mall_products->title ?? '';
                $value->product_picture = $value->mall_products->picture ?? '';
                $value->category_name = $value->mall_categories->title;
                $value->add_time = date('Y-m-d H:i:s', $value->add_time);
                $value->expired_time = date('Y-m-d H:i:s', $value->expired_time);
                if ($value->price == 0) {
                    $value->price = '免费';
                }
                if ($value->price == 9999) {
                    $value->price = '永久';
                }
                if ($value->state == 0) {
                    $value->use_status = '未使用';
                } elseif ($value->state == 1) {
                    $value->use_status = '使用中';
                } elseif ($value->state == 2) {
                    $value->use_status = '已过期';
                } else {
                    $value->use_status = '敬请期待';
                }
                unset($value->use_time);
                unset($value->type);
                unset($value->coin);
                unset($value->user_buyer);
                unset($value->user_owner);
                unset($value->mall_products);
                unset($value->mall_categories);
            }

        }
        return Response::sendList($list, [], $param);
    }

    /**
     * @api {get} /mall/mall_order_list_history 购买记录产品记录
     * @apiVersion 0.1.0
     * @apiName 购买记录产品记录
     * @apiGroup 个性商城
     * @apiParam {string} user_id_buyer     购买人，非必传
     * @apiParam {string} user_id_owner   拥有人，非必传
     * @apiParam {string} title     产品名称，非必传
     * @apiParam {number} category_id     产品分类id，非必传
     * @apiParam {string} add_time     购买时间，非必传
     * @apiParam {string} expired_time     过期时间，非必传
     * @apiParam {number} state     是否使用：0未使用1使用中2已过期，非必传
     * @apiParam {number} free     是否免费：1是 2否，非必传
     * @apiParam {number} forever     是否永久：1是  2否，非必传
     * @apiParam {number} day     天数，非必传
     * @apiParam {number} price     价格，非必传
     * @apiParam {number} page     页数（不传默认第一页），非必传
     * @apiParam {number} perPage     每页数据数量，非必传
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id(主键序号)": 434,
     * "user_id_buyer(购买者id)": 642801,
     * "user_id_owner（拥有者id）": 642801,
     * "product_id（产品id）": 29,
     * "price_id（价格id）": 29,
     * "expired_time（过期时间）": "2020-09-08 14:14:38",
     * "renew_count（无效字段）": 0,
     * "price（产品价格）": "免费",
     * "day（天数）": 1,
     * "state（使用状态：0未使用1使用中2已过期）": 2,
     * "add_time（购买时间）": "2020-09-07 14:14:38",
     * "category_id（分类id）": 2,
     * "buyer_nickname（购买者昵称）": "气泡用户859186",
     * "owner_nickname（拥有者昵称）": "气泡用户859186",
     * "product_name（产品名称）": "银光天马",
     * "product_picture（产品图片）": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5ed779265eb09.png",
     * "category_name（产品分类名称）": "坐骑",
     * "use_status（使用状态）": "已过期"
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 20,
     * "next": null,
     * "total": 1
     * },
     * "header": {
     * "user_id_buyer（搜索购买者）": "气泡",
     * "user_id_owner（搜索拥有者）": "气泡",
     * "title（产品标题）": "银光",
     * "category_id（分类id）": "2",
     * "add_time（购买时间）": "2020-09-07",
     * "expired_time（过期时间）": "2020-09-08",
     * "renew_count（无效字段）": "0",
     * "state（使用状态）": "2",
     * "free（是否免费）": "1",
     * "forever（是否永久）": "2",
     * "day（天数）": "1",
     * "price（产品价格）": "0"
     * }
     * }
     * }
     */
    public function mallOrderHistoryList(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'user_id_buyer' => 'filled',
                'user_id_owner' => 'filled',
                'title' => 'filled',
                'category_id' => 'filled|numeric',
                'add_time' => 'filled|date_format:"Y-m-d"',
                'expired_time' => 'filled|date_format:"Y-m-d"',
                'state' => 'filled|in:0,1,2',
                'free' => 'filled|in:1,2',
                'renew_count' => 'filled|numeric',
                'forever' => 'filled|in:1,2',
                'day' => 'filled|numeric',
                'price' => 'filled|numeric',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $param = $request->only(['user_id_buyer', 'user_id_owner', 'title', 'category_id', 'add_time', 'expired_time', 'state', 'free', 'forever', 'day', 'price','renew_count']);
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 20);
        $where_buyer = $where_owner = $where_product = $where_order = [];
        if (isset($param['user_id_buyer'])) {
            $user_id_buyer = $param['user_id_buyer'];
            if (is_numeric($user_id_buyer)) {//如果是数字就根据user_code查询
                $where_buyer[] = [function ($query) use ($user_id_buyer) {
                    $query->where('user_code', '=', $user_id_buyer);
                }];
            } else {
                $where_buyer[] = [function ($query) use ($user_id_buyer) {
                    $query->where('nickname', 'like', "%{$user_id_buyer}%");
                }];
            }
        }
        if (isset($param['user_id_owner'])) {
            $user_id_owner = $param['user_id_owner'];
            if (is_numeric($user_id_owner)) {//如果是数字就user_code查询
                $where_owner[] = [function ($query) use ($user_id_owner) {
                    $query->where('user_code', '=', $user_id_owner);
                }];
            } else {
                $where_owner[] = [function ($query) use ($user_id_owner) {
                    $query->where('nickname', 'like', "%{$user_id_owner}%");
                }];
            }
        }
        if (isset($param['title'])) {
            $title = $param['title'];
            $where_product[] = [function ($query) use ($title) {
                $query->where('title', 'like', "%{$title}%");
            }];
        }
        if (isset($param['renew_count'])) {
            $where_order[] = ['renew_count', $param['renew_count']];
        }
        if (isset($param['category_id'])) {
            $where_product[] = ['category_id', $param['category_id']];
        }

        if (isset($param['add_time'])) {
            $add_time = strtotime($param['add_time']);
            $where_order[] = [function ($query) use ($add_time) {
                $query->whereBetween('add_time', [$add_time, $add_time + 86400]);
            }];
        }
        if (isset($param['expired_time'])) {
            $expired_time = strtotime($param['expired_time']);
            $where_order[] = [function ($query) use ($expired_time) {
                $query->whereBetween('expired_time', [$expired_time, $expired_time + 86400]);
            }];
        }
        if (isset($param['state'])) {
            $where_order[] = ['state', $param['state']];
        }
        if (isset($param['free'])) {
            if ($param['free'] == 1) {
                $where_order[] = ['price', 0];
            }
            if ($param['free'] == 2) {
                $where_order[] = ['price', '>', 0];
            }
        }
        if (isset($param['price'])) {
            $where_order[] = ['price', $param['price']];
        }
        if (isset($param['forever'])) {
            if ($param['forever'] == 1) {
                $where_order[] = ['day', 9999];
            }
            if ($param['forever'] == 2) {
                $where_order[] = ['day', '>', 0];
                $where_order[] = ['day', '<', 9999];
            }
        }

        if (isset($param['day'])) {
            $where_order[] = ['day', $param['day']];
        }
        $all_where = [
            'where_buyer' => $where_buyer,
            'where_owner' => $where_owner,
            'where_product' => $where_product,
            'where_order' => $where_order,
        ];
        $list = app('repo_mall_orders_history')->MallOrderList($all_where, $page, $perPage);
        if ($list) {
            foreach ($list as $key => $value) {
                $value->buyer_nickname = $value->user_buyer->nickname ?? '';
                $value->owner_nickname = $value->user_owner->nickname ?? '';
                $value->product_name = $value->mall_products->title ?? '';
                $value->product_picture = $value->mall_products->picture ?? '';
                $value->category_name = $value->mall_categories->title;
                $value->add_time = date('Y-m-d H:i:s', $value->add_time);
                $value->expired_time = date('Y-m-d H:i:s', $value->expired_time);
                if ($value->price == 0) {
                    $value->price = '免费';
                }
                if ($value->price == 9999) {
                    $value->price = '永久';
                }
                if ($value->state == 0) {
                    $value->use_status = '未使用';
                } elseif ($value->state == 1) {
                    $value->use_status = '使用中';
                } elseif ($value->state == 2) {
                    $value->use_status = '已过期';
                } else {
                    $value->use_status = '敬请期待';
                }
                unset($value->use_time);
                unset($value->type);
                unset($value->coin);
                unset($value->user_buyer);
                unset($value->user_owner);
                unset($value->mall_products);
                unset($value->mall_categories);
            }
        }
        return Response::sendList($list, [], $param);
    }

    /**
     * @api {Get} /mall/nd_conversion_list 国庆节兑换列表
     * @apiGroup 补充接口-个性商城
     *
     * @apiParam {Int} gift_type 礼物类型：0：不限制；7：钥匙扣；8：抱枕
     * @apiParam {Int} user_code 用户编号
     * @apiParam {Int} mobile 用户手机号
     *
     * @apiSuccessExample {json} Response-Example
     * {
     *   "code":200,
     *   "data":{
     *      "current_page":1,
     *      "data":[
     *          {
     *              "id":"1", 序号
     *              "user_id":"121838677958514", 用户ID
     *              "user_no":"764554", 用户编号
     *              "mobile":"15959435345", 手机号
     *              "nickname":"呵呵", 昵称
     *              "gift_name":"钥匙扣1", 礼物名称
     *              "add_time":"2021-05-13 12:12:22", 创建时间
     *          }
     *      ],
     *      "first_page_url":"http://local.zxj.com/api/mch/mchlist?page=1",
     *      "from":1,
     *      "last_page":1,
     *      "last_page_url":"http://local.zxj.com/api/mch/mchlist?page=1",
     *      "next_page_url":null,
     *      "path":"http://local.zxj.com/api/mch/mchlist",
     *      "per_page":10,
     *      "prev_page_url":null,
     *      "to":1,
     *      "total":1
     *   }
     * }
     */
    public function ndConversionList(Request $request)
    {
        $giftType = $request->gift_type;
        $userCode = $request->user_code;
        $mobile = $request->mobile;

        $where = $whereIn = [];
        if ($giftType == 7) {
            $whereIn[] = ['nd.type', [5, 7]];
        } else if ($giftType == 8) {
            $whereIn[] = ['nd.type', [6, 8]];
        } else {
            $whereIn[] = ['nd.type', [5, 6, 7, 8]];
        }
        if ($userCode) {
            $where[] = ['u.user_no', '=', $userCode];
        }
        if ($mobile) {
            $where[] = ['u.mobile', '=', $mobile];
        }

        $list = app('model_national_day')->getListPaging($where, $whereIn, ['nd.id', 'nd.user_id', 'u.user_no', 'u.mobile', 'ud.nickname', 'nd.name as gift_name', 'nd.add_time']);
        foreach ($list as &$v) {
            $v->add_time = date('Y-m-d H:i:s', $v->add_time);
        }
        return $list;
    }

}
